from subprocess import Popen, PIPE, STDOUT
import time
from collections import *
import threading
lock = threading.Lock()
from  helpFunc import  *
n = 0
import time
if isWindows:
    exe = 'd:/PuTTY/plink.exe'
    #exe = 'C:/Program Files/PuTTY/plink.exe'
else:
    exe = 'plink'
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('plinkLog')
handler = RotatingFileHandler('plinkLog.log', maxBytes=20*1024, backupCount=1)
formatter = logging.Formatter("%(asctime)s %(message)s",
                              "%Y-%m-%d %H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)    

def work(s):
    global n 
    add = False
    try:
        p = Popen([exe, '-ssh','%s@%s'%(logName,serverIp),'-pw',logPw], stdin=PIPE, stdout=PIPE, stderr=STDOUT, encoding='UTF8')
        response = p.stdout.readline()    
        logger.warning(response)
        lock.acquire()
        n+=1
        print ('ssh ok',s,response[:10])
        add = True
        lock.release()  
        p.stdin.write('echo %s\n'%('a'*3000))
        p.stdin.flush()          
        for i in range(100):
            time.sleep(3)
            p.stdin.write('echo %s %s\n'%(s,i))
            p.stdin.flush()  
            response = p.stdout.readline()
            logger.warning(response)
        p.kill()
        lock.acquire()
        n-=1
        print('ssh close',s)
        lock.release()         
    except Exception as e:
        try:
            p.kill()
        except:
            pass
        print (e)
        if add:
            lock.acquire()        
            n-=1
            print('ssh close',s)
            lock.release()    
def main():            
    l = deque()
    co = 0
    startTime = 0
    while True:
        time.sleep(1)
        if time.monotonic()-startTime<5:
            continue
        ok = True
        lock.acquire()
        if n>=10:
            ok = False
        lock.release()
        if not ok:
            continue
        co += 1
        t = threading.Thread(target=work,args=(co,))
        t.setDaemon(True)
        t.start()
        l.append(t)   
        startTime = time.monotonic()    
        while len(l)>50:
            l.popleft()     
if __name__=='__main__':
    main()